package com.snail.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.common.core.constant.CacheConstants;
import com.snail.common.core.constant.CommonConstants;
import com.snail.common.core.enums.BizStatus;
import com.snail.common.core.exception.ServiceException;
import com.snail.common.core.utils.PageUtils;
import com.snail.common.core.utils.SpringUtils;
import com.snail.common.core.utils.ValidationUtils;
import com.snail.common.core.web.page.PageResult;
import com.snail.common.excel.converter.BizStatusConverter;
import com.snail.common.redis.service.RedisService;
import com.snail.system.api.domain.SysTenant;
import com.snail.system.api.dto.SysTenantDto;
import com.snail.system.api.query.SysTenantQuery;
import com.snail.system.mapper.SysTenantMapper;
import com.snail.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.snail.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.validation.Validator;
import java.time.Year;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 租户管理Service业务层处理
 * @Author: snail
 * @CreateDate: 2024-04-30
 * @Version: V1.0
 */
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private RedisService redisService;

    @PostConstruct
    public void init() {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getStatus, CommonConstants.STATUS_ENABLE);
        queryWrapper.orderByAsc(SysTenant::getSortNum);
        //加载多租户
        List<SysTenant> tenantList = baseMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(tenantList)) {
            redisService.setCacheObject(CacheConstants.TENANT_KEY, tenantList);
        }
    }

    @Override
    public PageResult<SysTenant> selectSysTenantPage(SysTenantQuery query) {
        Page<SysTenant> page = PageUtils.buildPage(query);
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        //租户号
        queryWrapper.eq(StringUtils.isNotEmpty(query.getTenantId()), SysTenant::getTenantId, query.getTenantId());
        //租户名
        queryWrapper.like(StringUtils.isNotEmpty(query.getTenantName()), SysTenant::getTenantName, query.getTenantName());
        //状态
        queryWrapper.eq(StringUtils.isNotEmpty(query.getStatus()), SysTenant::getStatus, query.getStatus());
        page = baseMapper.selectPage(page, queryWrapper);
        return PageUtils.pageResult(page);
    }

    @Override
    public SysTenant getSysTenantById(Long id) {
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertSysTenant(SysTenant sysTenant) {
        save(sysTenant);
        //更新缓存
        init();
        return sysTenant.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSysTenant(SysTenant sysTenant) {
        updateById(sysTenant);
        //更新缓存
        init();
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSysTenantByIds(Long[] ids) {
        int batch = baseMapper.deleteBatchIds(Arrays.asList(ids));
        return batch == ids.length;
    }

    @Override
    public List<SysTenant> selectSysTenantList(SysTenantQuery query) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(SysTenant sysTenant) {
        if(sysTenant.getId() == null ||  StringUtils.isEmpty(sysTenant.getStatus())){
            throw new ServiceException("租户id和状态不能为空!");
        }
        LambdaUpdateWrapper<SysTenant> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysTenant::getStatus,sysTenant.getStatus());
        updateWrapper.eq(SysTenant::getId,sysTenant.getId());
        return update(updateWrapper);
    }


    @Override
    public String checkExcelData(SysTenant sysTenant) {
        StringBuffer error = new StringBuffer();
        ValidationUtils.checkProperty(SpringUtils.getBean(Validator.class), sysTenant, excludeCheckFiled(sysTenant), SysTenant.class, error);
        if(StringUtils.isNotEmpty(sysTenant.getStatus())){
            sysTenant.setStatus(BizStatus.converterCode(sysTenant.getStatus()));
        }
        return error.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveExcelData(List<SysTenant> dataList) {
        saveBatch(dataList);
        init();
    }
}
